import userApi from "@/api/modules/user";
import { ElLoading } from "element-plus";
const user = {
  namespaced: true,
  state: {
    // 令牌
    token: sessionStorage.getItem("token") || ""
    // userName: "",
    // permission: null
  },
  mutations: {
    setToken(state, Token) {
      state.token = Token;
      sessionStorage.setItem("token", Token);
    }
    // setPermission(state, Arr) {
    //   state.permission = Arr;
    // },
    // setUserName(state, name) {
    //   state.userName = name;
    // }
  },
  actions: {
    // user login
    login({ commit, dispatch }, parmas) {
      return new Promise((resolve, reject) => {
        // let loginLoading = ElLoading.service({
        //   lock: true,
        //   text: "正在登录...",
        //   background: "rgba(0, 0, 0, 0.7)"
        // });
        userApi
          .login(parmas)
          .then(async res => {
            if (res.data.token) {
              commit("setToken", res.data.token);
             let routes = await dispatch("Permission/MergeRoutes", res.data.token, {
                root: true
              });
              console.log('User-routes',routes)
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch(err => {
            reject(err);
          });
        // loginLoading.close();
      });
    },
    getUserInfo({ commit, dispatch },token) {
      return new Promise((resolve, reject) => {
        userApi
          .getUserInfo(token)
          .then(async res => {
            // commit("setPermission", res.data.permission);
            // commit("setUserName", res.data.userName);
            // await dispatch("Permission/MergeRoutes", res.data.permission, {
            //   root: true
            // });
            resolve(res.data);
          })
          .catch(err => {
            reject(err);
          });
      });
    }
  }
};
export default user;
